<?php


namespace App\Services\Member\Services;

use App\Services\Member\Models\UserRole;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Services\Member\Models\Role;
use Illuminate\Support\Facades\Auth;
use App\Services\Member\Models\UserJoinRoleRecord;
use App\Services\Member\Interfaces\RoleServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;

class RoleService implements RoleServiceInterface
{
    protected $userService;

    public function __construct(UserServiceInterface $userService)
    {
        $this->userService = $userService;
    }

    public function all(): array
    {
        return Role::query()->with(['shop', 'privileges'])->orderBy('weight')->get()->toArray();
    }


    /**
     * @param int $id
     * @return array
     */
    public function find(int $id)
    {
        return Role::query()->findOrFail($id)->toArray();
    }

    public function findCompanyRole(int $userId, int $shopId)
    {
        $userRole = UserRole::query()->where('user_id', $userId)->where('company_id', $shopId)->first();
        return $userRole ? $userRole->toArray() : [];
    }

    /**
     * @param int $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public function get(int $id)
    {
        return Role::query()->with(['shop','privileges'])->find($id);

    }

    /**
     * @param int $page
     * @param int $size
     *
     * @return array
     */
    public function userRolePaginate(int $userId, int $page, int $size): array
    {
        $query = UserJoinRoleRecord::query()
            ->with(['user:id,nick_name,avatar,mobile', 'role:id,name'])
            ->where('user_id', $userId)
            ->orderByDesc('created_at');

        $total = $query->count();
        $list = $query->forPage($page, $size)->get()->toArray();

        return compact('total', 'list');
    }



    /**
     * @param array $roleRecord
     * @param array $role
     * @param int $charge
     */
    public function userJoinRole(int $userId, array $role, int $charge,int $isForeverMembership): void
    {
        // 当前用户是免费会员
        DB::transaction(function () use ($userId, $role, $charge,$isForeverMembership) {
            $now = Carbon::now();
            $expiredAt = (clone $now)->addDays($role['expire_days']);
            // 创建购买记录
            UserJoinRoleRecord::create([
                'company_id' => $role['company_id'],
                'user_id' => $userId,
                'role_id' => $role['id'],
                'charge' => $charge,
                'started_at' => $now,
                'expired_at' => $expiredAt,
                'is_forever_membership'=>$isForeverMembership
            ]);

            $this->userService->changeRole($userId, $role['id'],$role['company_id'], $expiredAt->toString(),$isForeverMembership);
        });
    }

    public function userContinueRole(int $userId,array $userRole,array $role, int $charge,int $isForeverMembership): void
    {
        // 用户续费套餐
        DB::transaction(function () use ($userId,$userRole,$role, $charge,$isForeverMembership) {
            $startAt = Carbon::parse($userRole['expired_at']);
            $startAt = $startAt->gt(Carbon::now()) ? $startAt : Carbon::now();
            $expiredAt = (clone $startAt)->addDays($role['expire_days']);
            // 创建购买记录
            UserJoinRoleRecord::create([
                'company_id' => $role['company_id'],
                'user_id' => $userId,
                'role_id' => $role['id'],
                'charge' => $charge,
                'started_at' => $startAt,
                'expired_at' => $expiredAt,
            ]);
            // 修改user表
            $this->userService->changeRole($userId, $role['id'],$role['company_id'],$expiredAt->toString(),$isForeverMembership);
        });
    }
    public function getUserRecommendRole(int $userId,int $shopId,int $size)
    {
        $roleIds  =  UserRole::query()
            ->select(['role_id','user_id','company_id'])
            ->whereUserId($userId)
            ->whereCompanyId($shopId)
            ->get()
            ->pluck('role_id')
            ->toArray();
        return Role::query()->whereNotIn('id',$roleIds)->select(['id','title','thumb'])->paginate($size);

    }
}
